package com.yang.config;

import com.yang.pojo.SysRole;
import com.yang.pojo.SysUser;
import com.yang.pojo.SysUserRole;
import com.yang.service.SysRoleService;
import com.yang.service.SysUserRoleService;
import com.yang.service.SysUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author 杨天可
 * @Date 2021/6/10 15:36
 * @Version 1.0
 */
public class ShiroRealm extends AuthorizingRealm {

    @Resource
    SysUserRoleService sysUserRoleService;
    @Resource
    SysRoleService sysRoleService;
    @Resource
    SysUserService sysUserService;

    /*
    权限验证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        SysUser sysUser = (SysUser)principalCollection.getPrimaryPrincipal();
        List<SysUserRole> sysUserRoles = sysUserRoleService.findRoleByUserId(sysUser.getId());
        /*用户 ---  角色 是一对多关系，一个用户可能拥有多种角色*/
        for (SysUserRole roleId:
                sysUserRoles) {
            SysRole sysRole = sysRoleService.findById(roleId.getRoleId());
            /*从主体获取角色信息*/
            authorizationInfo.addRole(sysRole.getName());
        }
        return authorizationInfo;
    }

    /*
    身份认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        /*获取当前主体的用户名*/
        String username = (String)authenticationToken.getPrincipal();
        SysUser sysUser = sysUserService.findByPhone(username);
        if (sysUser == null){
            return null;
        }else{
            return new SimpleAuthenticationInfo(
                    sysUser,
                    sysUser.getPassword(),
                    /*  salt=UUID+salt  */
                    ByteSource.Util.bytes(sysUser.getCredentialsSalt()),
                    getName()
            );
        }
    }
}
